﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Data;
using System.Web.Services.Protocols;
using System.Threading;
using PSLibrary = Microsoft.Office.Project.Server.Library;


namespace CometeTeste
{
    class Program
    {
        private const string PROJECT_SERVER_URL =
            "http://zdemo/pwa/_vti_bin/psi/";
       // public SvcProject.ProjectDataSet dsProjectDataSet = null;
        //SvcProject.Project objProject = null;
       
        
        static void Main(string[] args)
        {
            bool isWindowsUser = true;
            
            // Create an instance of the project object.
            ProjectDerived project = new ProjectDerived();
           // SvcProject.Project project = new SvcProject.Project();
            SvcProject.Project project2 = new SvcProject.Project();
            
            project.Url = PROJECT_SERVER_URL + "Project.asmx";
            
            project.Credentials = CredentialCache.DefaultCredentials;
            project2.Credentials = CredentialCache.DefaultCredentials;
            ///////////////////////////////////
            
            
            //////////////////////////////////////

            try
            {
                
                // The program works on a Windows-auth-only computer if you comment-out the
                // following line. The line is required on a multi-authentication computer.
                project.CookieContainer = GetLogonCookie();
                
                //project.UnsafeAuthenticatedConnectionSharing = isWindowsUser;
                //project.EnforceWindowsAuth = isWindowsUser;

                // Get a list of all published projects. 
                // Use ReadProjectStatus instead of ReadProjectList,
                // because the permission requirements are lower.
                SvcProject.ProjectDataSet projectDs =
                    project.ReadProjectStatus(Guid.Empty,
                        SvcProject.DataStoreEnum.PublishedStore,
                        string.Empty,
                        (int)PSLibrary.Project.ProjectType.Project);

                
                Console.WriteLine(string.Format(
                    "There are {0} published projects.",
                    projectDs.Project.Rows.Count));
                SvcProject.ProjectDataSet prjdset = project.ReadProjectList(); 

                ///////////////////////////////////////////////////////create project

                SvcProject.ProjectDataSet.ProjectRow projectRwC = projectDs.Project.NewProjectRow();
                Guid _projectGUID = Guid.NewGuid(); // new GUID for each project
                projectRwC.PROJ_UID = _projectGUID;
                projectRwC.PROJ_NAME = "My new Project";
                //projectRwC.PROJ_INFO_START_DATE = System.DateTime.Now;
                projectRwC.PROJ_TYPE = 1; //0 is for project and 1 is for template

                projectDs.Project.AddProjectRow(projectRwC);


                project.QueueCreateProject(Guid.NewGuid(), projectDs, false);
                project.QueuePublish(Guid.NewGuid(), _projectGUID, true, string.Empty);

                //when project is created bu default it is checked out
                // we must checkin the project.
                project2.QueueCheckInProject(Guid.NewGuid(), _projectGUID, true, Guid.Empty, "Checking by system");

                //////////////////////////////////////////////////////////
                foreach (SvcProject.ProjectDataSet.ProjectRow projectRow in prjdset.Project)
                {
                    //The data set returned by ReadProjectList() method only contain some basic information of the projects
                    Guid projectID = projectRow.PROJ_UID;
                    string projectName = projectRow.PROJ_NAME;
                    //string projectfield2 = projectRow.WPROJ_DESCRIPTION;
                    Console.WriteLine("GUID of Project : {0}", projectID);
                    Console.WriteLine("bulished project in PWA and Owner: {0}", projectName);
                    //Get the project information from Working Store
                    SvcProject.ProjectDataSet workingProjectDataSet = project.ReadProject(projectID, SvcProject.DataStoreEnum.WorkingStore);
                    SvcProject.ProjectDataSet.ProjectRow workingProjectRow = workingProjectDataSet.Project[0];

                    //Get the project information from Published Store
                    SvcProject.ProjectDataSet publishedProjectDataSet = project.ReadProject(projectID, SvcProject.DataStoreEnum.PublishedStore);
                    SvcProject.ProjectDataSet.ProjectRow publishedProjectRow = publishedProjectDataSet.Project[0];
                    
                    //Project Stage information is stored in the Working Store
                    //Guid projectStageID = workingProjectRow.STAGE_UID;
                    //string projectStageName = workingProjectRow.STAGE_NAME;

                    //Project work space information is stored in the Published Store
                    //string projectWorkSpaceName = publishedProjectRow.WPROJ_STS_SUBWEB_NAME;
                }

        
    
            
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.Write("Press any key to continue...");
                Console.ReadKey(false);
            }

            
        }

        private static CookieContainer GetLogonCookie()
        {
            // Create an instance of the loginWindows object.
            LoginWindowsDerived loginWindows = new LoginWindowsDerived();
            loginWindows.EnforceWindowsAuth = true;
            loginWindows.Url = PROJECT_SERVER_URL + "LoginWindows.asmx";
            loginWindows.Credentials = CredentialCache.DefaultCredentials;

            loginWindows.CookieContainer = new CookieContainer();

            if (!loginWindows.Login())
            {
                // Login failed; throw an exception.
                throw new UnauthorizedAccessException("Login failed.");
            }
            return loginWindows.CookieContainer;
        }
    }

    // Derive from LoginWindows class; include additional property and 
    // override the Web request header.
    class LoginWindowsDerived : SvcLoginWindows.LoginWindows
    {
        public bool EnforceWindowsAuth { get; set; }

        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest request = base.GetWebRequest(uri);

            if (this.EnforceWindowsAuth)
            {
                request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            }
            return request;
        }
    }

    // Derive from Project class; include additional property and 
    // override the Web request header.
    class ProjectDerived : SvcProject.Project
    {
        public bool EnforceWindowsAuth { get; set; }

        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest request = base.GetWebRequest(uri);

            if (this.EnforceWindowsAuth)
            {
                request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            }
            return request;
        }
    }

}
